// Copyright Viet-Dung D. Hoang 2008
// All rights reserved.

// Modified by Minh-Tri Pham 2009


#ifndef SDOPENCV_POLYGONAL_INTEGRATOR_H
#define SDOPENCV_POLYGONAL_INTEGRATOR_H

#include <cxcore.h>

#include <sdopencv/polygon.hpp>

namespace sdopencv
{
    typedef double intype;

    class PolygonalIntegrator
    {
    // ---------------------------------------------------------------------------------------
    // public data
    // ---------------------------------------------------------------------------------------
    public:
        int r2;
        int max_width, max_height;   // max width and max height for images

        // image
        int width, height, wstep;
        IplImage* img;
        uchar *img_data;

        // direction
        int dnum, dnum1;
        int dx[201], dy[201];

        int coe_n, coe_x[1001], coe_y[1001];  // max = 2*r
        intype coe_v[1001];
        int ver_x, ver_y[1001];

        // integral
        int **vertical_sum;
        intype ***integral;

        // look-up table
        int** lu_dir;


    // ---------------------------------------------------------------------------------------
    // private methods
    // ---------------------------------------------------------------------------------------
    private:
        void init_memory();
        void cal_directions();
        void cal_vertical_sum();
        void create_lookup_table();
        void preprocess();

        // helpers
        void add_coe(intype v, int x, int y);
        void cal_coefficient1(int d);
        void cal_coefficient2(int d);
        intype cal_integral(int d, int x, int y);


    // ---------------------------------------------------------------------------------------
    // public methods
    // ---------------------------------------------------------------------------------------
    public:
        PolygonalIntegrator(int max_width, int max_height, int r2);
        ~PolygonalIntegrator();

        bool input_image(IplImage *img);
        intype integrate(const CvPolygon& p);
    };
}

#endif
